package com.sdy.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
public class LibLoader {
    public static void loadLib(String libName) {
        String filename = libName;
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")){
            filename = filename.concat(".dll");
        } else if (os.toLowerCase().startsWith("linux")){
            filename = filename.concat(".so");
        } else if (os.toLowerCase().startsWith("mac")){
            filename = filename.concat(".jnilib");
        }
        String resourcePath = "/".concat(filename);
        String folderName = System.getProperty("java.io.tmpdir").concat("/jnilib/").concat(UUID.randomUUID().toString()).concat("/");
        File folder = new File(folderName);
        folder.mkdirs();
        File libFile = new File(folder, filename);
//        if (libFile.exists()) {
//            System.load(libFile.getAbsolutePath());
//        } else {
            try {
                InputStream in = LibLoader.class.getResourceAsStream(resourcePath);
                FileUtils.copyInputStreamToFile(in,libFile);
                in.close();
                System.load(libFile.getAbsolutePath());
            } catch (Exception e) {
                String errorMsg = "Failed to load required lib: ".concat(libName);
                log.error(errorMsg, e);
                throw new RuntimeException(errorMsg, e);
            }
//        }
    }
}
